//
//  APIManager.m
//  village_ios
//
//  Created by mac on 2019/8/10.
//  Copyright © 2019 com.sw.village. All rights reserved.
//

#import "APIManager.h"
#import "SYProgressHUD.h"
#import "UserManager.h"
#import "UIWindow+Extension.h"
#import "LoginController.h"
#define UploadImage @""
#define Host_Server @"localhost" //localhost api.mmbb123.com
#define TOKEN_ERROR_CODE 700
#define SUCCESS_CODE 200

@implementation APIManager


+ (NSString *)URLRequestStringWithURL:(NSString *)urlstr dict:(NSDictionary *)dict{
    
    NSMutableString *URL = [NSMutableString stringWithFormat:@"%@%@",Host_Server,urlstr];
    //获取字典的所有keys
    NSArray * keys = [dict allKeys];
    
    //拼接字符串
    for (int j = 0; j < keys.count; j ++){
        NSString *string;
        if (j == 0){
            //拼接时加？
            string = [NSString stringWithFormat:@"&%@=%@", keys[j], dict[keys[j]]];
            
        }else{
            //拼接时加&
            string = [NSString stringWithFormat:@"&%@=%@", keys[j], dict[keys[j]]];
        }
        //拼接字符串
        [URL appendString:string];
        
    }
    return URL;
}
//#define kkkey @"6eeb990828c443c3df7b909822377e54"

+ (void)requestWithUrlString:(NSString *)UrlString
                      params:(NSDictionary *)params
                      method:(NSString *)method
                     success:(Success)success
                     failure:(Failure)failure {
    
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict addEntriesFromDictionary:params];
    
    NSMutableDictionary *header = [NSMutableDictionary dictionary];
    if ([UserManager sharedInstance].token) {
        /**
         [{"key":"Authorization","value":"Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwiZXhwIjoxNTY2MzE3NTI1LCJpYXQiOjE1NjU3MTI3MjV9.TfaoAqiKJOY08ipCGEhZGt9VkES2P1dfo5CeHWfsg5tLqnexbtSX1HS1qzClcz6kD4leCGqQ9RYJ7nE0W-lcsA","description":""}]
         */
        NSString *key = [UserManager sharedInstance].token;
        [header addEntriesFromDictionary:@{@"Authorization":[NSString stringWithFormat:@"Bearer %@",key]}];

    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
    serializer.acceptableContentTypes= [NSSet setWithObjects:@"text/html", nil];
    manager.responseSerializer = serializer;
    
    if ([method isEqualToString:@"GET"]) {
        
        UrlString = [self URLRequestStringWithURL:UrlString dict:dict];
        dict = [NSMutableDictionary dictionary];
    }
    [manager POST:UrlString parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *jsonDict = responseObject;
        NSInteger code = 0;
        if (jsonDict[@"code"]) {
            code = [jsonDict[@"code"] integerValue];
        }
        if (code != SUCCESS_CODE) {
            [SYProgressHUD showInfoText:jsonDict[@"datas"]];
            if(code == TOKEN_ERROR_CODE) {
                [LoginController presentNaviLoginController:[UIWindow currentViewController] loginSuccess:^{
                    if (success) {
                        success(nil);
                    }
                }];
            } else {
                if (failure) {
                    failure(nil);
                }
            }
        }else {
            //通知主线程刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success) {
                    success(jsonDict[@"data"]);
                }
            });
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure) {
            failure(error);
        }
        [SYProgressHUD hide];
    }];

}

+ (void)uploadImageToServerWithImage:(UIImage *)image
                                type:(NSString *)type
                             success:(Success)success
                             failure:(Failure)failure{
    NSString *uploadURL = [NSString stringWithFormat:@"%@?type=%@",UploadImage,type];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:uploadURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:UIImagePNGRepresentation(image) name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg"];
    } error:nil];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
    serializer.acceptableContentTypes= [NSSet setWithObjects:@"text/plain", nil];
    manager.responseSerializer = serializer;
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
            [SYProgressHUD showFailureText:@"上传图片失败，请重试"];
        } else {
            NSLog(@"%@ %@", response, responseObject);
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                if (success) {
                    success(responseObject);
                }
            }
        }
    }];
    [uploadTask resume];
}
@end
